<template>
  <section>
    <!--订单基础信息-->
    管理员创建订单——274#api
    <el-form label-width="90px" size="mini">
      <el-form-item label="订单标题：">
        <el-input v-model="orderForm.title" style="width: 20%" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="选择用户：">
        <el-select v-model="selCustomer"  :filterable="true" remote :reserve-keyword="false" size="mini" allow-create
                   default-first-option  placeholder="请输入姓名" :remote-method="remoteMethod" value-key="id">
          <el-option v-for="(customer,index) in customerList" :key="index" :label="customer.name" :value="customer" v-if="customerList">
            <span style="float: left">{{ customer.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.phone }}</span>
          </el-option>
        </el-select>
        <el-select v-model="selMember" value-key="id" v-if="memberList && memberList.length>0" size="mini">
          <el-option v-for="(member,index) in memberList" :key="index" :label="member.userName" :value="member" >
            <span style="float: left">{{ member.userName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ member.phone }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择商品：">
        <el-select v-model="selGoods" placeholder="商品" size="mini" value-key="id">
          <el-option v-for="goods in goodsList" :key="goods.id" :label="goods.name" :value="goods"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品Sku：">
        <el-select v-model="selGoodsSku" placeholder="商品规格" size="mini"  @visible-change="selSkuBtn" value-key="id">
          <el-option v-for="goodsSku in goodsSkuList" :key="goodsSku.id" :label="goodsSku.props" :value="goodsSku"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!--订单项-->
    <el-row>
      <el-table :data="orderItemsForm">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="规格" prop="title"  width="130">
        </el-table-column>
        <el-table-column label="单价" prop="price"width="80">
        </el-table-column>
        <el-table-column label="编码" prop="sn" width="150">
        </el-table-column>
        <el-table-column label="数量" width="150">
          <template slot-scope="scope">
            <div class="numBox">
              <div  @click='increase(scope.row)' >
                <i  class="el-icon-plus" size="mini" ></i>
              </div>
              <div class="num">
                {{scope.row.num}}
              </div>
              <div  @click='decrease(scope.row)' >
                <i class="el-icon-minus" size="mini"></i>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="totalPrice">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row v-for="(customerId,index) in scope.row.data.customerIds" :key="customerId.id" v-if="scope.row.needCustomerId && customerInMemberList && customerInMemberList.length>0">
              <el-select v-model="scope.row.data.customerIds[index]" value-key="id" size="mini">
                <el-option v-for="(customer,index) in customerInMemberList" :key="index" :label="customer.name" :value="customer.id">
                  <span style="float: left">{{ customer.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.phone }}</span>
                </el-option>
              </el-select>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-button size="mini" type="primary" @click="subOrderBtn">提交订单</el-button>
  </section>
</template>

<script>
  import { mapActions,mapGetters} from 'vuex'
  import DateFormat from '@/common/date-formater'
  import errHandler from '@/assets/errHandler.js'
  export default {
    name: "examineOrder",
    data() {
      return {
        orderForm:{
          title:'',
          memberId:'',
          departmentId:'',
          orderItems:null,
          orderDiscount: ''
        },
        orderItemsForm:[],
        selCustomer:null,
        selMember:null,
        memberList:null,
        customerList:null,
        selGoods:null,
        goodsList:null,
        selGoodsSku:null,
        goodsSkuList:null,
        showPayDialog:false,
        customerInMemberList:null
      }
    },
    created(){
      this.orderForm.departmentId=this.department.id
      this.getGoodsList(this.department.id)
    },
    computed: {
      ...mapGetters(['department']),
    },
    watch:{
      selCustomer(nv,ov){
        if(nv){
          this.selMember=null
          this.memberList=null
        }
        this.getMembers(nv.name)
        if(typeof(nv) === "string"){
          //跳出新建用户的对话框
          this.$message('未找到该用户，请确认用户是否存在！')
        }
      },
      selGoods(nv,ov){
        let needCustomerId=null
        if(nv.goodsType.data.needCustomerId){
          //获取规格列表
          needCustomerId=true
        }else {
          needCustomerId=false
        }
        this.getGoodsSkuList(needCustomerId,nv.id)
      },
      selGoodsSku(nv,ov){
        if(nv){
          let sku = nv
          sku.title = sku.props
          let orderItems = this.orderItemsForm
          if(orderItems && orderItems.length >0){//如果当前订单规格存在并且有内容，就找一找选中的规格在订单规格内有没有
            let index = orderItems.findIndex(i => i.sn === sku.sn)
            if(index >= 0){//存在这个sku，那就数量+1
              this.increase(orderItems[index])
            }else {//不存在，就增加这个sku
              let tmp = {...sku,edit:false,num:1}
              tmp.totalPrice = tmp.num*sku.price
              orderItems.push(tmp)
            }
          }else {//如果当前订单规格不存在或者没有内容，就直接增加sku
            //不存在，就增加这个sku
            let tmp = {...sku,edit:false,num:1}
            tmp.totalPrice = tmp.num*sku.price
            orderItems.push(tmp)
          }
        }
      },
      selMember(nv,ov){
        console.log(nv)
        if(nv){
          if(nv.customers.length<=0){
            this.$message('该账户下还未绑定用户，请确认！')
            return
          }
          this.customerInMemberList=nv.customers
        }
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      getMembers(keywords){
        this.fetch({name:"getMembers",data:{keywords}})
          .then(res=>{
            if(res.content.length<=0){
              this.$message('该用户还未绑定账户，请确认！')
              return
            }
            this.memberList=res.content
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getGoodsList(departmentId){
        //还有mall商品
        this.fetch({name:"getGoodsList",data:{departmentId}})
          .then(res=>{
            this.goodsList = res.content
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getGoodsSkuList(n,goodsId){
        console.log(n)
        this.fetch({name:"getGoodsSkuList",data:{goodsId}})
          .then(res=>{
            // console.log('sku内容————————————',res)
            if(n){
              res.forEach(r=>{
                r.needCustomerId=true
                r.data={customerIds: ['']}
              })
            }
            this.goodsSkuList = res
            // console.log(this.goodsSkuList)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      remoteMethod(keywords) {
        clearTimeout()
        setTimeout(()=>{
          this.fetch({name:"getUserList",data:{keywords}})
            .then(res=>{
              // console.log(res)
              this.customerList=res.content
            })
            .catch(err=>{
              console.log(err)
              errHandler.handle(this,err)
            })},500)
      },
      increase(row){//增加数量
        // console.log(row)
        row.num +=1
        row.totalPrice +=row.price
        row.data.customerIds.push('')
      },
      decrease(row){//减少数量
        row.num -=1
        row.totalPrice -=row.price
        row.data.customerIds.splice(row.data.customerIds.length-1,1)
        if(row.num === 0){
          let index = this.orderItemsForm.findIndex(o => o.id === row.id )
          if(index >=0){
            this.orderItemsForm.splice(index,1)
          }
        }
      },
      selSkuBtn(e){
        if(e === true){
          this.selGoodsSku = null
        }
      },
      subOrderBtn(){
        // console.log(this.selMember)
        this.orderForm.memberId=this.selMember.id
        let orderData = this.makeOrderItems(this.orderForm,this.orderItemsForm)
        this.orderForm.orderItems=orderData
        // console.log(this.orderForm)
        this.createOrderByManager(this.orderForm)
      },
      makeOrderItems(order,items){
        order.orderItems=[]
        for(let i=0;i<items.length;i++){
          let tmp = items[i]
          let detail = this.exchangeTitle(tmp.props)
          let o = {
            title:tmp.props,
            price:tmp.price,
            totalPrice:tmp.totalPrice,
            num:tmp.num,
            sn:tmp.sn,
            data:{...tmp.data,...detail}
          }
          order.orderItems.push(o)
        }
        return JSON.stringify(order.orderItems)
      },
      createOrderByManager(data){
        console.log('管理员创建订单——————————————————————————',data)
        this.fetch({name:"createOrderByManager",data:data})
          .then(res=>{
            console.log('创建订单byAdmin——————————',res)
            this.$message('提交成功')
            // this.$router.push({path:'/orderManagement/allOrder/'+res})
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      exchangeTitle(title){
        let tmp={}
        let titles=title.split(';')
        console.log(titles)
        titles.forEach(t=>{
          let kv = t.split(':')
          let k=kv[0]
          let v=kv[1]
          tmp[k]=v
        })
        // console.log(tmp)
        return tmp
      },
      updateOrderItem(o,data){
        this.fetch({name:"updateOrderItem",data:{id:o.id,data}})
          .then(res=>{
            console.log(res)
            // this.goodsList = res.content
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      }
    }
  }
</script>

<style scoped>
  .numBox{
    /*border: 1px solid crimson;*/
    display: flex;
    justify-content: left;
    align-items: center;
  }
  .num{
    border: 1px solid darkgrey;
    width: 40px;
    margin:0 10px 0 10px;
    text-align: center;
    justify-content: center;
  }
</style>
